<!--
 * @Author: wangming
 * @Date: 2021-03-30 13:44:09
 * @LastEditors: wangming
 * @LastEditTime: 2022-06-20 11:15:00
 * @Description: file content
-->
<template>
  <div class="ks-row-middle">
    <el-badge class="mr20" v-if="VUE_APP_USER === 'APP'" :value="getMsgNum > 0 ? getMsgNum : ''">
      <span @click="handleOpenModel('message')" class="mr20 tip">
        <i style="font-size: 20px" class="el-icon-bell"></i>
        {{ $t("sys.message") }}
      </span>
    </el-badge>

    <el-badge v-if="VUE_APP_USER === 'APP'" :value="getProcessNum > 0 ? getProcessNum : ''">
      <span class="mr20 tip" @click="handleOpenModel('process')">
        <i style="font-size: 20px" class="el-icon-share"></i>
        {{ $t("sys.process") }}
      </span>
    </el-badge>
    <el-link v-if="VUE_APP_USER === 'ADMIN'" :underline="false" class="preview" icon="el-icon-video-play f14"
      @click="handlePreview">
      <span class="dib pl5 f14">应用预览</span>
    </el-link>
    <el-link v-if="VUE_APP_USER === 'ADMIN'" :underline="false" class="ks-row-middle"
      href="https://hancode.yuque.com/books/share/6a3fb47f-1caf-410d-9569-90d003f2fef5?#" target="_blank">
      <i class="iconfont iconicon_tishishuoming f14"> </i>
      <span class="dib pl5 f14">帮助中心</span>
    </el-link>
    <el-dropdown v-if="VUE_APP_USER === 'APP'" trigger="click" class="poi ml15 lh1" @command="handleLang"
      placement="bottom">
      <earth theme="outline" size="26" fill="#666" :strokeWidth="3" class="lh1" />
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item :key="i.key" :command="i.key" v-for="i in langOptions" :disabled="$i18n.locale === i.key">{{
            i.region
        }}</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
    <el-dropdown trigger="click" class="poi" @command="handleCommand" placement="bottom">
      <div class="ks-row-middle">
        <el-avatar style="background-color: #fff" :src="getUserVal.avatar || defaultAvatar" class="ml20" size="small"
          icon="el-icon-user-solid"></el-avatar>
        <span v-if="getUserVal.name" class="ml10 name__limit" :title="getUserVal.name">{{ getUserVal.name }}
        </span>
      </div>
      <el-dropdown-menu slot="dropdown" v-if="VUE_APP_USER === 'APP'">
        <el-dropdown-item command="usercenter">{{
            $t("sys.personal_setting")
        }}</el-dropdown-item>
        <el-dropdown-item command="appqrcode" v-if="VUE_APP_ROOT_URL === './' && !MOS_ENABLED">{{
            $t("sys.app_setting")
        }}</el-dropdown-item>
        <el-dropdown-item command="logout" divided v-if="!isWxworkOrDingtalk">{{
            MOS_ENABLED ? "退出应用" : $t("sys.safe_exit")
        }}</el-dropdown-item>
      </el-dropdown-menu>
      <el-dropdown-menu slot="dropdown" v-else>
        <el-dropdown-item command="workben">工作台</el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>
<script>
import { Accesstoken, appUnique } from "@/utils/auth";
import stores from "store2";
import { TOKEN, MOS_ENABLED, APP_TOKEN } from "@/utils/const";
import { mapGetters, mapActions } from "vuex";
import { getHmprocessruntimeTaskTodoCount } from "@/apis/paas/HmProcessRuntimeController.js";
import { getMsgWebmessageUnreadCount } from "@/apis/paas/MsgWebMessageController.js";
import ServerMqtt from "@/utils/mqttConfig";
import EventBus from "@/utils/eventBus";
import { Earth } from "@icon-park/vue";
import { getHmi18nlocaleList } from "@/apis/paas/HmI18nLocaleController.js";
import { CliI18n } from "@/i18n";
import defaultAvatar from "@/assets/image/defaultAvatar.png";
import { browser } from "@/utils/browser";
export default {
  components: { Earth },
  data() {
    return {
      defaultAvatar,
      langOptions: [
        {
          label: "简体中文",
          value: "cn",
        },
        {
          label: " 英语（英国）",
          value: "en",
        },
      ],
      VUE_APP_ROOT_URL: process.env.VUE_APP_ROOT_URL,
      VUE_APP_USER: process.env.VUE_APP_USER,
      timer: null,
      client: null,
    };
  },
  computed: {
    ...mapGetters(["getUserVal", "getMsgNum", "getProcessNum", "MOS_ENABLED"]),
    topic() {
      let unique = appUnique || "master";
      const topic = unique + "_" + this.getUserVal.id + "_MESSAGE";
      return topic;
    },
    isWxworkOrDingtalk() {
      let { wxwork, dingtalk } = browser.versions;
      return wxwork || dingtalk;
    },
  },
  created() {
    if (this.VUE_APP_USER === "APP") {
      this.initProcessTimer();
      this.initMqtt();
      this.getlocaleList();
    } else {
      this.timer = null;
    }
  },
  mounted() {
    // 消息配置更新之后初始化
    EventBus.$on("sendSysMsgConfigChange", () => {
      if (this.VUE_APP_USER === "APP") {
        this.initMqtt();
      }
    });
  },
  async beforeDestroy() {
    clearInterval(this.timer);
    EventBus.$off("sendSysMsgConfigChange");
    try {
      ServerMqtt.msgWebconfig &&
        ServerMqtt.msgWebconfig.unsubscribeMqtt(this.topic, "mqtt_bar");
    } catch (error) { }
  },
  methods: {
    ...mapActions(["logout"]),
    async getlocaleList() {
      this.langOptions = await getHmi18nlocaleList();
    },
    async handleLang(lang) {
      await CliI18n.changeLang(lang);
      window.location.reload();
      //其他第三方交互
      const event = new CustomEvent("onLanguageChange", {
        detail: { lang },
      });
      window.dispatchEvent(event);
    },
    // 定时5s获取页面消息
    initProcessTimer() {
      if (!this.timer) {
        this.timer = setInterval(async () => {
          if (!Accesstoken.getAccessToken()) {
            return;
          }
          if (stores.get(MOS_ENABLED)) {
            if (!stores.get(TOKEN)) {
              return;
            }
          }
          const msgData = await getHmprocessruntimeTaskTodoCount();
          this.$store.commit("SET_PROCESS_NUM", msgData);
        }, 30000);
      }
    },
    handleCommand(key) {
      switch (key) {
        case "appqrcode":
          this.$router.push({ name: "app-qrcode" });
          break;
        case "logout":
          this.logout();

          break;
        case "workben":
          // 返回工作台
          window.location.href = window.location.origin;
          break;
        case "message":
          // this.$router.push({ name: 'app-message' })
          break;
        case "process":
          this.$router.push({ name: "app-process" });
          break;
        case "usercenter":
          this.$router.push({ name: "app-usercenter" });
          break;
        default:
          break;
      }
    },
    handleOpenModel(key) {
      switch (key) {
        case "message":
          this.$router.push({ name: "app-message" });
          break;
        case "process":
          this.$router.push({ name: "app-process" });
          break;
        default:
          break;
      }
    },
    handlePreview() {
      if (process.env.NODE_ENV === "production") {
        stores.set(APP_TOKEN, "");
        // const url = `${window.location.origin}/preview/app:${appUnique}`;
        const url = window.location.origin + window.location.pathname.replace('designer','preview');
        window.open(url);
      } else {
        this.$message.warning("npm run serve:app");
      }
    },
    async initMqtt() {
      // 获取未读数据
      const num = await getMsgWebmessageUnreadCount();
      this.$store.commit("SET_MSG_NUM", num || 0);
      try {
        let mqttInstance = await ServerMqtt.getDefaultMqtt();
        mqttInstance.subscribeMqtt(this.topic, "mqtt_bar", () => {
          this.$store.commit("SET_MSG_NUM", this.getMsgNum + 1);
        });
      } catch (error) { }
    },
  },
};
</script>
<style scoped>
.ks-row-middle .el-badge>>>.el-badge__content.is-fixed {
  position: absolute;
  top: 5px;
  right: 20px;
  -webkit-transform: translateY(-50%) translateX(100%);
  transform: translateY(-50%) translateX(100%);
}

.dropdowmItem.el-badge>>>.el-badge__content.is-fixed {
  position: absolute;
  top: 12px;
  right: 24px;
  font-size: 12px;
  height: 16px;
  line-height: 16px;
  padding: 0 5px;
  -webkit-transform: translateY(-50%) translateX(100%);
  transform: translateY(-50%) translateX(100%);
}

.tip:hover {
  cursor: pointer;
}

.preview {
  margin-right: 20px;
}

.name__limit {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
